package 链表;

import org.junit.Test;

/**
 * @author aodre , QQ : 480029069
 * @date 2023/3/16 17:20
 */
public class leetcode21合并两个有序链表 {

    /*
      直接在原链表上面修改
       采用这个 哨兵机制,还是很不错的!
     */

    public ListNode solution(ListNode l1,ListNode l2){
        if(l1 == null){
            return l2;
        }
        if(l2 == null){
            return l1;
        }
        // 把 cur 当作一个 sentinel 哨兵
        ListNode cur = new ListNode(0),root;
        root =  cur;
        while(l1 != null && l2 != null){
            if(l1.val <= l2.val){
                cur.next = l1;
                l1 = l1.next;
//                cur = cur.next;
            }
            else{
                cur.next = l2;
                l2 = l2.next;
//                cur = cur.next;
            }
            cur = cur.next;
        }
        // 一个链表走到末尾, 一个链表没有 走到末尾
        cur.next = l1 == null ? l2 : l1;

        return root.next;
    }


    @Test
    public void test(){
        ListNode l1 = new ListNode(1);
        ListNode l2 = new ListNode(1);
        l1.next = new ListNode(2);
        l1.next.next = new ListNode(4);

        l2.next = new ListNode(3);
        l2.next.next = new ListNode(4);
//        System.out.println();
        solution(l1,l2);

    }

    class ListNode{
        int val;
        ListNode next;
        public ListNode(int val){
            this.val = val;
        }
    }




    public ListNode solve(ListNode l1,ListNode l2){

        ListNode sentinel = new ListNode(-1), cur = sentinel;

        while(l1 != null && l2 != null){
            if(l1.val < l2.val){
                cur.next = l1;
                l1 = l1.next;
            }else{
                cur.next = l2;
                l2 = l2.next;
            }
            cur = cur.next;
        }

        cur.next = l1 == null ? l2 : l1;
        return sentinel.next;
    }





}
